package com.example.cart.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.room.util.StringUtil;

import com.example.cart.R;
import com.example.cart.application.CustomApplication;
import com.example.cart.dao.ProductDao;
import com.example.cart.database.ShoppingDatabase;
import com.example.cart.entity.Cart;
import com.example.cart.entity.Product;
import com.example.cart.utils.ToastUtils;

import java.util.List;

public class CartIndexActivity extends AppCompatActivity {

    private ShoppingDatabase shoppingDatabase;

    private ImageView ivBack;

    private ScrollView svCartItems;

    private LinearLayout llCartItems;
    private Button btnClearCart;
    private TextView tvTotalAmount;
    private Button btnSettle;
    private LinearLayout llEmptyPrompt;
    private Button btnJumpToShoppingIndex;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_cart_index);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        shoppingDatabase = CustomApplication.getInstance().getShoppingDatabase();

        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(v -> jumpToShoppingIndex());

        svCartItems = findViewById(R.id.sv_cart_items);
        llCartItems = findViewById(R.id.ll_cart_items);
        btnClearCart = findViewById(R.id.btn_clear_cart);
        tvTotalAmount = findViewById(R.id.tv_totoal_amount);
        btnSettle = findViewById(R.id.btn_settle);
        llEmptyPrompt = findViewById(R.id.ll_empty_prompt);
        btnJumpToShoppingIndex = findViewById(R.id.btn_jump_to_shopping_index);

        btnClearCart.setOnClickListener(v -> {
            llCartItems.removeAllViews();
            shoppingDatabase.cartDao().deleteAll();
            svCartItems.setVisibility(View.INVISIBLE);
            llEmptyPrompt.setVisibility(View.VISIBLE);
        });
        btnJumpToShoppingIndex.setOnClickListener(v -> jumpToShoppingIndex());
        btnSettle.setOnClickListener(v -> {
            ToastUtils.show(this, "当前功能还未开放，敬请期待吧！");
        });

        showCartItemList();
    }

    public void jumpToShoppingIndex() {
        Intent intent = new Intent();
        intent.setClass(this, ShoppingIndexActivity.class);
        startActivity(intent);
    }

    public void showCartItemList() {
        // 查询购物车商品列表
        List<Cart> cartList = shoppingDatabase.cartDao().query(20, 0);
        if (cartList.isEmpty()) {
            // 隐藏商品列表，展示提示信息
            svCartItems.setVisibility(View.INVISIBLE);
            llEmptyPrompt.setVisibility(View.VISIBLE);
            return;
        }

        // 先清空购物车列表
        llCartItems.removeAllViews();

        ProductDao productDao = shoppingDatabase.productDao();

        // 获取屏幕的宽度
        int screenWidth = getResources().getDisplayMetrics().widthPixels;
        GridLayout.LayoutParams layoutParams = new GridLayout.LayoutParams();
        layoutParams.width = screenWidth;
        layoutParams.height = 50;

        Double totalAmount = 0.0;
        for (Cart cartItem : cartList) {
            // 查询商品详情
            Product product = productDao.queryById(cartItem.getProductId());
            // 根据布局文件cart_item.xml实例化一个布局视图对象
            View vCartItem = getLayoutInflater().inflate(R.layout.cart_item, null);
            ImageView ivPic = vCartItem.findViewById(R.id.iv_pic);
            try {
                ivPic.setImageURI(Uri.parse(product.getPicPath()));
            } catch (Exception e) {
                // ignore
            }

            TextView tvProductName = vCartItem.findViewById(R.id.tv_product_name);
            tvProductName.setText(product.getName());

            TextView tvProductDesc = vCartItem.findViewById(R.id.tv_product_desc);
            tvProductDesc.setText(product.getDesc());

            TextView tvQuantity = vCartItem.findViewById(R.id.tv_quantity);
            tvQuantity.setText(String.valueOf(cartItem.getQuantity()));

            TextView tvPrice = vCartItem.findViewById(R.id.tv_product_price);
            tvPrice.setText(String.format("%.2f", product.getPrice()));

            TextView tvAmount = vCartItem.findViewById(R.id.tv_product_amount);
            tvAmount.setText(String.format("%.2f", cartItem.getAmount()));

            totalAmount += cartItem.getAmount();

            llCartItems.addView(vCartItem);
        }

        // 设置总金额
        tvTotalAmount.setText(String.valueOf(String.format("%.2f", totalAmount)));

        svCartItems.setVisibility(View.VISIBLE);
        llEmptyPrompt.setVisibility(View.INVISIBLE);
    }

}